package com.lf.freezingpoint.common.initialization;

import com.lf.freezingpoint.entity.SysPermission;
import com.lf.freezingpoint.entity.SysRole;
import com.lf.freezingpoint.service.SysPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

@Component
@Order(1)
public class PermissionInitialization implements CommandLineRunner {
    private static final Logger logger = Logger.getLogger(PermissionInitialization.class.toString());

    @Autowired
    private SysPermissionService sysPermissionService;

    @Autowired
    private RedisTemplate redisTemplate;

    public void permissionInfoToRedis() {
        List<SysPermission> sysPermissionList = sysPermissionService.getAllPermissionInfo();
        sysPermissionList.forEach(sysPermission -> {
            List<SysRole> sysRoles = sysPermission.getSysRoles();
            List<String> roles = new ArrayList<>();
            sysRoles.forEach(sysRole -> roles.add(sysRole.getRoleKey()));
            redisTemplate.opsForValue().set(sysPermission.getPermissionUrl(), roles);
        });
        logger.info("permission权限初始化成功");
    }

    @Override
    public void run(String args[]) {
        permissionInfoToRedis();
    }
}
